<?php
    /*
        $db = \WZ_Singleton::WZ_Activerecord('users')->getAdapter();
        $authDb = new \Zend_Auth_Adapter_DbTable ($db, 'users', 'login', 'mdp');
        $authDb->setIdentity('gplusquellec');
        $authDb->setCredential(md5('mdp'));
        $auth = \WZ_Auth::factory($authDb);
        \WZ_Auth::isAuth();
        \WZ_Auth::getIdentity()->getName();
    */
    
    
    class WZ_Auth
    {
        public static function factory(\Zend_Auth_Adapter_DbTable $auth)
        {
            $result = \Zend_Auth::getInstance()->authenticate($auth);
            if ($result->getCode() == 1) {
                $data = $auth->getResultRowObject();
                \Zend_Auth::getInstance()->getStorage()->write($data);
            }
            return $result;
        }
        
        public static function getIdentity()
        {
            $identity = \Zend_Auth::getInstance()->getStorage()->read();
            $identityObject = new \WZ_Identity;
            $vars = get_object_vars($identity);
            foreach ($vars as $key => $value) {
                $setter = 'set' . ucfirst(strtolower($key));
                $identityObject->$setter($value);
            }
            return $identityObject;
        }
        
        public static function isAuth()
        {
            return \Zend_Auth::getInstance()->hasIdentity();
        }
        
        public static function logout()
        {
            if (\Zend_Auth::getInstance()->hasIdentity()) {
                \Zend_Auth::getInstance()->clearIdentity();
                return true;
            }
            return false;
        }
        
        public static function getSession()
        {
            return new \Zend_Session_Namespace('WZAuth');
        }
    }
    
    class WZ_Identity 
    {
        public function __call($method, $args)
        {
            $methodCalled = substr($method, 0, 3);
            if ($methodCalled == 'get') {
                $var = strtolower(substr($method, 3));
                if (isset($this->$var)) {
                    return $this->$var;
                }
                return null;
            } elseif ($methodCalled == 'set') {
                $var = strtolower(substr($method, 3));
                $this->$var = $args[0];
            }
        }
    }